package com.tpv.app.volley.demo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonObject;
import com.tpv.app.volley.demo.util.BitmapLruCache;
import com.tpv.app.volley.demo.util.FileUpdateRequest;
import com.tpv.app.volley.demo.util.GsonRequest;
import com.tpv.app.volley.demo.util.GsonVolleyListener;
import com.tpv.app.volley.demo.util.HTTPUtils;
import com.tpv.app.volley.demo.util.IPermission;
import com.tpv.app.volley.demo.util.JsonObjectRequest;
import com.tpv.app.volley.demo.util.PermissionRequestActivity;
import com.tpv.app.volley.demo.util.PhotoSelectUtils;
import com.tpv.app.volley.demo.util.VolleyListener;
import com.tpv.app.volley.demo.util.VoteBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity implements IPermission
{
    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView mTvLog;
    private ImageView mIvShow;
    private Bitmap mBitmap;
    private final String baseUrl = "http://192.168.5.2:8080";
    private PhotoSelectUtils mMPhotoSelectUtils;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvLog = findViewById(R.id.tv_log);
        mIvShow = findViewById(R.id.iv_show);
        final Map<String, String> params = new HashMap<>();
        findViewById(R.id.btn_option_a).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                params.put("option", "A");
                sendPost(params);
            }
        });
        findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                sendGet();
            }
        });
        findViewById(R.id.btn_get_json).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
              sendGetJson();
            }
        });
        findViewById(R.id.btn_get_image).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                downloadImage();
            }
        });
        findViewById(R.id.btn_update_image).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                PermissionRequestActivity.permissionRequest(MainActivity.this,PermissionRequestActivity.CAMERA_PERMISSONS,PermissionRequestActivity.ASK_REQUEST_CODE,MainActivity.this);
            }
        });
        init();
    }
    private void init()
    {
        // 1、创建LQRPhotoSelectUtils（一个Activity对应一个LQRPhotoSelectUtils）
        // 4、当拍照或从图库选取图片成功后回调
//true裁剪，false不裁剪
        mMPhotoSelectUtils = new PhotoSelectUtils(this, new PhotoSelectUtils.PhotoSelectListener()
        {
            @Override
            public void onFinish(File outputFile, Uri outputUri)
            {
                // 4、当拍照或从图库选取图片成功后回调
                uploadImage(outputFile);
            }
        }, false);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        mMPhotoSelectUtils.attachToActivityForResult(requestCode,resultCode,data);
    }
    
    private void uploadImage(File file)
    {
        VolleyLog.step = 0;
        Map<String, Object> params = new HashMap<>();
        Map<String, File> fileMap = new HashMap<>();
        Map<String, List<File>> multiFileMap = new HashMap<>();
        params.put("userId", 12312);
        params.put("name", "washabi");
        params.put("key", "haha");
        params.put("age", 12);
        fileMap.put("upload", file);
        List<File> files = new ArrayList<>();
        files.add(file);
        multiFileMap.put("upload", files);
        FileUpdateRequest request = new FileUpdateRequest(baseUrl + "/user/uploadImg", params,fileMap ,null, new VolleyListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                log(error);
            }
            
            @Override
            public void onResponse(String response)
            {
                log(response);
                mTvLog.setText(mTvLog.getText().toString().trim() + "\n" + response);
    
            }
        });
        Volley.newRequestQueue(this).add(request);
    }
    
    private void downloadImage()
    {
        VolleyLog.step = 0;
        
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        ImageLoader imageLoader = new ImageLoader(requestQueue, new BitmapLruCache(1024 * 1024 * 8));
        imageLoader.get(baseUrl + "/image/a123131.PNG", new ImageLoader.ImageListener()
        {
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate)
            {
                mBitmap = response.getBitmap();
                mIvShow.setImageBitmap(mBitmap);
            }
            
            @Override
            public void onErrorResponse(VolleyError error)
            {
                log(error);
            }
        });
    }
    
    private void sendPost(Map<String, String> params)
    {
        VolleyLog.step = 0;
        HTTPUtils.post(this, baseUrl + "/user/vote", params, new VolleyListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                log(error);
            }
            
            @Override
            public void onResponse(String response)
            {
                mTvLog.setText(mTvLog.getText().toString().trim() + "\n" + response);
                log(response);
            }
        });
    }
    private void sendGetJson()
    {
        VolleyLog.step = 0;
        GsonRequest<VoteBean> request= new GsonRequest<>(Request.Method.GET, baseUrl + "/user/json",null, VoteBean.class, new GsonVolleyListener<VoteBean>()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                log(error);
            }
    
            @Override
            public void onResponse(VoteBean response)
            {
                String code = response.getCode();
                String message = response.getMessage();
                mTvLog.setText(mTvLog.getText().toString().trim()+"\n"+",code:"+code+",message:"+message);
                log(response);
            }
        });
        Volley.newRequestQueue(this).add(request);
    }


    
    private void sendGet()
    {
        VolleyLog.step = 0;
        HTTPUtils.get(this, baseUrl + "/user/info", new VolleyListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                log(error);
            }
            
            @Override
            public void onResponse(String response)
            {
                mTvLog.setText(mTvLog.getText().toString().trim() + "\n" + response);
                log(response);
            }
        });
    }
    
    private void log(Object msg)
    {
        Log.e(TAG, "" + msg);
    }
    
    @Override
    public void permissionGranted(int requestCode)
    {
        mMPhotoSelectUtils.selectPhoto();
    }
    
    @Override
    public void permissionCancel(int requestCode)
    {
    }
    
    @Override
    public void permissionDeny(int requestCode, List<String> denyList)
    {
    }
}
